// pages/home/home.js
import computedBehavior from 'miniprogram-computed'
const APP = getApp()

Page({
  behaviors: [computedBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    bannerList: [{
        path: '',
        img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/d7abb68ac50f82412d325f305cc62fb0.jpeg?thumb=2&w=1226&h=460&f=webp&q=10'
      },
      {
        path: '',
        img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/e023dd94c146d0f27f7ae8e98213abff.jpg?thumb=1&w=1226&h=460&f=webp&q=90'
      },
      {
        path: '',
        img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/02b6f2a85191a4806e6fefb38a12890a.jpg?thumb=1&w=1226&h=460&f=webp&q=90'
      },
      {
        path: '',
        img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/bbcd4ba87a306e51f033f80d7ed65cce.jpg?thumb=1&w=1226&h=460&f=webp&q=90'
      },

    ],
    safeList: [{
        text: '官方商城',
        image: '/images/home/diamond.png'
      },
      {
        text: '正品保障',
        image: '/images/home/safety.png'
      },
      {
        text: '满69包邮',
        image: '/images/home/privac_open.png'
      },
    ],
    stickyEnum: [],
    pageSize: 10,
    activeSticky: '',
    activeTar: null,
    isSticky: false,
    tabs: [],
    activeTab: 0,
    _touchX: 0,
    _isTabChanging: false,
    list: [],
  },
  computed: {
    leftList(data) {
      return data.list.filter((item, index) => !(index % 2))
    },
    rightList(data) {
      return data.list.filter((item, index) => !!(index % 2))
    },
  },

  goProductDetail(event) {
    wx.navigateTo({
      url: '/pages/product/product?id=' + event.currentTarget.dataset.product
    })
  },

  // tab内容左右滚动事件
  scroll(e) {
    console.log('scroll', e)
    if (this.data._isTabChanging) return
    console.log(e.detail.scrollLeft % this.data.screenWidth)
    let newActive = Math.round(e.detail.scrollLeft / this.data.screenWidth)
    if (newActive == this.data.activeSticky) return
    this.setData({
      activeSticky: newActive,
      tabStickyToView: 'tabSticky' + newActive,
    })
  },
  // tab内容左右滚动开始事件
  dragstart(e) {
    console.log('dragstart', e)
    this.data._isTabChanging = false
    this.data._touchX = e.detail.scrollLeft
  },

  // sticky tab滚动事件
  onStickyScroll(obj) {
    const {
      scrollTop,
      isFixed
    } = obj.detail
    console.log(scrollTop, isFixed)
    if (this.data.isSticky != isFixed) {
      this.setData({
        isSticky: isFixed,
      })
    }
  },

  // tab点击事件
  tabClick(event) {
    console.log(event)
    var index = event.currentTarget.dataset.index
    this.setData({
      activeSticky: this.data.stickyEnum[index].type,
      activeTar: this.data.stickyEnum[index],
      tabStickyToView: 'tabSticky' + index,
    })
    let tar = this.data.stickyEnum[index]

    //  滚动到第一个
    if (this.data.isSticky) {
      wx.pageScrollTo({
        scrollTop: this.data._stickyScrollTop,
        // selector: "#scrollTar",
        duration: 0,
      })
    }

    // 已经加载过数据
    if (tar.hasFirstLoaded) {
      wx.nextTick(() => {
        this.setData({
          list: tar.list,
        })
      })
    } else {
      // 加载当前tab下的第一页数据
      // 设置加载状态
      wx.showLoading({
        title: '加载中...',
      })
      this.setData({
        [`stickyEnum[${index}].loading`]: true
      })
      wx.$http.get('product/getProductList', {
        data: {
          pageNum: 1,
          pageSize: this.data.pageSize,
          tab_name: tar.type
        }
      }).then(res => {
        console.log(res)
        wx.hideLoading()
        tar.list = res.data.records
        tar.finish = res.data.records.length >= res.data.total
        tar.loading = false
        tar.hasFirstLoaded = true
        tar.page = 1
        this.setData({
          list: res.data.records,
          [`stickyEnum[${index}]`]: tar,
          activeTar: tar
        })
      })
    }
  },

  goSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this
    this.setData({
      navTop: APP.globalData.navTop,
      navHeight: APP.globalData.navHeight,
      navLeft: APP.globalData.navLeft,
      navRight: APP.globalData.navRight,
      screenWidth: APP.globalData.screenWidth,
    })

    wx.$http.get('product/getUserSku').then(res => {
      wx.setStorageSync('cartCount', res.data.reduce((prev, cur) => {
        return prev + cur.num
      }, 0))
    })

    wx.createSelectorQuery().select('#scrollTar').boundingClientRect(function (rect) {
      console.log(rect.top)
      that.data._stickyScrollTop = rect.top - APP.globalData.navTop - APP.globalData.navHeight
    }).exec()

    wx.$http.get('product/getProductType', {
      page: 1,
      pageSize: this.data.pageSize,
    }).then(res => {
      console.log(res)
      let stickyEnum = [{
          title: '精选',
          type: '',
          hasFirstLoaded: true,
          loading: false,
        },
        ...res.data.map(item => {
          return {
            title: item,
            type: item,
            hasFirstLoaded: false,
            loading: false,
          }
        })
      ]
      this.setData({
        stickyEnum,
        activeTar: stickyEnum[0],
      })

      wx.$http.get('product/getProductList', {
        data: {
          pageNum: 1,
          pageSize: this.data.pageSize,
        }
      }).then(res => {
        this.setData({
          'list': res.data.records,
          'stickyEnum[0].list': res.data.records,
          'stickyEnum[0].finish': res.data.records.length >= res.data.total,
          'stickyEnum[0].page': 1,
        })
      })

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('reach Bottom')
    let index = this.data.stickyEnum.findIndex(i => i.type === this.data.activeSticky)
    let tar = this.data.stickyEnum[index]
    if (!tar.finish) {
      wx.showLoading({
        title: '加载中...',
      })
      this.setData({
        [`stickyEnum[${index}].loading`]: true
      })

      wx.$http.get('product/getProductList', {
        data: {
          pageNum: tar.page + 1,
          pageSize: this.data.pageSize,
          tab_name: tar.type
        }
      }).then(res => {
        console.log(res)
        tar.list = tar.list.concat(res.data.records)
        tar.finish = tar.list.length >= res.data.total
        tar.loading = false
        tar.page = tar.page + 1
        this.setData({
          list: tar.list,
          [`stickyEnum[${index}]`]: tar,
          activeTar: tar
        })
        wx.hideLoading()
      })
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})